<template>
  <div class="dept-manage">
    <h2 class="page-title">科室管理</h2>

    <!-- 新增/编辑弹窗 -->
    <el-dialog title="编辑科室" v-model="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="deptForm" label-width="100px">
        <el-form-item label="科室名称" prop="department_name">
          <el-input v-model="form.department_name" placeholder="请输入科室名称"></el-input>
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-input v-model="form.level" placeholder="填写数字（如1、2）"></el-input>
        </el-form-item>
        <el-form-item label="上级科室ID" prop="parent_id">
          <el-input v-model="form.parent_id" placeholder="无上级填NULL"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="create_time">
          <el-input 
            v-model="form.create_time" 
            placeholder="创建时间" 
            disabled 
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确认保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查询与操作 -->
    <div class="search-bar">
      <el-input 
        v-model="searchKey" 
        placeholder="搜索科室名称" 
        clearable 
        style="width: 240px; margin-right: 10px;"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleAdd">新增科室</el-button>
    </div>

    <!-- 科室列表 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="department_id" label="ID" width="80"></el-table-column>
      <el-table-column prop="department_name" label="科室名称"></el-table-column>
      <el-table-column prop="level" label="层级" width="80"></el-table-column>
      <el-table-column prop="parent_id" label="上级科室ID" width="120"></el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button 
            type="text" 
            icon="el-icon-edit" 
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button 
            type="text" 
            icon="el-icon-delete" 
            text-color="red" 
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 批量删除按钮 -->
    <div style="margin-top: 10px;">
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
      >
        批量删除
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { 
  ElMessage, 
  ElDialog, 
  ElForm, 
  ElFormItem, 
  ElInput, 
  ElButton, 
  ElTable, 
  ElTableColumn,
  ElMessageBox 
} from 'element-plus';

// 模拟科室数据（与你提供的数据库结构一致）
const mockDeptData = [
  { department_id: 1, department_name: '内', level: 1, parent_id: 0, create_time: '2022-03-25 15:03:18' },
  { department_id: 2, department_name: '外科', level: 1, parent_id: null, create_time: '2022-03-25 15:04:03' },
  { department_id: 3, department_name: '妇科', level: 1, parent_id: null, create_time: '2022-03-25 15:04:19' },
  { department_id: 4, department_name: '儿科', level: 1, parent_id: null, create_time: '2022-03-25 15:04:29' },
  { department_id: 5, department_name: '传染病', level: 1, parent_id: null, create_time: '2022-03-25 15:05:21' },
  { department_id: 6, department_name: '五官科', level: 1, parent_id: null, create_time: '2022-03-25 15:05:28' },
  { department_id: 7, department_name: '中医科', level: 1, parent_id: null, create_time: '2022-03-25 15:05:36' },
  { department_id: 8, department_name: '检验科', level: 1, parent_id: null, create_time: '2022-03-25 15:05:47' },
  { department_id: 9, department_name: '放射科', level: 1, parent_id: null, create_time: '2022-03-25 15:05:57' },
  { department_id: 10, department_name: '超声科', level: 1, parent_id: null, create_time: '2022-03-25 15:06:04' },
  { department_id: 11, department_name: '胃镜科', level: 1, parent_id: null, create_time: '2022-03-25 15:06:11' },
  { department_id: 12, department_name: '药剂科', level: 1, parent_id: null, create_time: '2022-03-25 15:06:17' },
  { department_id: 13, department_name: '行政科室', level: 1, parent_id: null, create_time: '2022-03-25 15:06:27' },
  { department_id: 14, department_name: '神经内科', level: 2, parent_id: 1, create_time: '2022-03-25 15:07:02' },
  { department_id: 20, department_name: '心外科', level: 2, parent_id: 2, create_time: '2022-04-12 16:40:47' },
  { department_id: 28, department_name: '妇产科', level: 2, parent_id: 3, create_time: '2022-04-12 18:03:03' }
];

// 响应式数据
const tableData = ref(mockDeptData);
const searchKey = ref('');
const dialogVisible = ref(false);
const form = reactive({
  department_id: '', // 新增时自动生成，编辑时回显
  department_name: '',
  level: '',
  parent_id: '',
  create_time: ''
});
const rules = reactive({
  department_name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' }
  ],
  level: [
    { 
      required: true, 
      message: '请输入层级', 
      trigger: 'blur' 
    },
    {
      pattern: /^\d+$/,
      message: '请输入有效的数字层级',
      trigger: 'blur'
    }
  ]
});
const selectedRows = ref([]); // 批量删除用

// 生命周期：初始化数据
onMounted(() => {
  // 可在此处模拟从 localStorage 或其他存储加载数据
});

// 搜索功能
const handleSearch = () => {
  if (!searchKey.value) {
    tableData.value = mockDeptData;
    return;
  }
  const lowerKey = searchKey.value.toLowerCase();
  tableData.value = mockDeptData.filter(item => 
    item.department_name.toLowerCase().includes(lowerKey)
  );
};

// 新增科室
const handleAdd = () => {
  // 重置表单
  form.department_id = '';
  form.department_name = '';
  form.level = '';
  form.parent_id = '';
  form.create_time = '';
  dialogVisible.value = true;
};

// 编辑科室
const handleEdit = (row) => {
  // 回显数据
  form.department_id = row.department_id;
  form.department_name = row.department_name;
  form.level = row.level;
  form.parent_id = row.parent_id;
  form.create_time = row.create_time;
  dialogVisible.value = true;
};

// 保存（新增/编辑）
const handleSave = () => {
  if (form.department_id) {
    // 编辑逻辑：找到对应项替换
    const index = tableData.value.findIndex(item => item.department_id === form.department_id);
    if (index!== -1) {
      tableData.value[index] = { ...form };
      ElMessage.success('编辑成功！');
    }
  } else {
    // 新增逻辑：自动生成 department_id（简单模拟递增）
    const maxId = Math.max(...tableData.value.map(item => item.department_id));
    form.department_id = maxId + 1;
    // 优化 create_time 格式
    form.create_time = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-');
    tableData.value.push({ ...form });
    ElMessage.success('新增成功！');
  }
  dialogVisible.value = false;
};

// 删除科室
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '此操作将永久删除该科室, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    tableData.value = tableData.value.filter(item => item.department_id!== row.department_id);
    ElMessage.success('删除成功！');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的科室');
    return;
  }
  ElMessageBox.confirm(
    '确定删除选中的' + selectedRows.value.length + '个科室？',
    '提示',
    { type: 'warning' }
  ).then(() => {
    const ids = selectedRows.value.map(item => item.department_id);
    tableData.value = tableData.value.filter(item =>!ids.includes(item.department_id));
    selectedRows.value = []; // 清空选中
    ElMessage.success('批量删除成功！');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 监听选中项变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
</script>

<style scoped>
.dept-manage {
  padding: 20px;
}
.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: right;
}
</style>